<template>
  <div class="question-detail-wrapper">
    <div v-if="typeof(this.qiangId) != 'undefined'" class="question-answer-title">
      <span>请您在<em class="ehance-text">{{ countDown }}</em>内回答，到时自动取消</span>
    </div>
    <div class="question-info-item">
      <div class="question-header">
        <img class="avatar" :src="question.asker.avatar" alt="" />
        <span class="name">{{ question.asker.nickname }}</span>
        <span class="price">￥{{ question.reward }}</span>
      </div>
      <div class="question-content">
        <div class="question-desc">
          <p class="question-text full-desc">{{ question.text }}</p>
          <image-previewer :images="question.attachments"></image-previewer>
          <div class="question-tags">
            <span v-if="question.purpose" class="tag-item tag-red">{{ question.purpose }}</span>
            <span v-if="question.catalog" class="tag-item">{{ question.catalog.name }}</span>
          </div>
          <span class="ask-time">{{ question.pastTimeStr }}提问</span>
        </div>
      </div>
    </div>
    <div class="answer-action-wrapper">
      <button :class="['action-btn', !canAnswer ? 'btn-disabled' : '']" @click="answer">回答</button>
      <div class="action-tips-wrapper">
        <p>仅「{{ question.master_level.name }}」及以上可以回答</p>
      </div>
      <div v-if="question.process < 2" class="action-tips-wrapper">
        <p>还剩余{{ question.remainHour }}小时</p>
        <p>已经有{{ answerData.results.length }}人回答，系统将依据请教者对所有答案的评分按比例分配奖金和积分</p>
      </div>
      <div v-if="question.process == 2" class="action-tips-wrapper">
        <p>问题已解答</p>
      </div>
      <div v-if="question.process == 3" class="action-tips-wrapper">
        <p>问题已关闭</p>
      </div>
    </div>
    <ul class="answers-wrapper">
      <li v-for="(item, index) in answerData.results" class="answer-item">
        <div class="answer-header">
          <img class="avatar" :src="item.replier.avatar" alt="" />
          <span class="name">{{ item.replier.nickname }} {{ item.replier.title }}</span>
          <span v-if="item.reward" class="price">￥{{ item.reward }}</span>

        </div>
        <div class="answer-content">
          <image-previewer v-if="item.attachments.length" :images="item.attachments"></image-previewer>
          <p v-if="item.text" class="question-text full-desc">{{ item.text }}</p>
        </div>
        <div class="answer-bubble">
          <bubble @payed="payAnswer" :objectId="item.id" :isBought="isAsker ? true : item.is_bought" :audioUrl="item.audio" :localId="item.localId" :type="1" reward="1" :seconds="item.audio_length" :index="index"></bubble>
        </div>
        <div v-if="item.stars" class="answer-check-wrapper">
          <span class="check-desc">{{ item.stars }}星</span>
        </div>

        <div v-if="item.stars" class="answer-rate-wrapper">
          <img v-if="item.stars >=1" src="../../assets/icon/icon_star_selected.png" alt="" />
          <img v-else src="../../assets/icon/icon_star.png" alt="" />
          <img v-if="item.stars >=2" src="../../assets/icon/icon_star_selected.png" alt="" />
          <img v-else src="../../assets/icon/icon_star.png" alt="" />
          <img v-if="item.stars >=3" src="../../assets/icon/icon_star_selected.png" alt="" />
          <img v-else src="../../assets/icon/icon_star.png" alt="" />
          <img v-if="item.stars >=4" src="../../assets/icon/icon_star_selected.png" alt="" />
          <img v-else src="../../assets/icon/icon_star.png" alt="" />
          <img v-if="item.stars >=5" src="../../assets/icon/icon_star_selected.png" alt="" />
          <img v-else src="../../assets/icon/icon_star.png" alt="" />
        </div>

        <div class="answer-item-footer">
          <span class="answer-time">{{ item.pastTimeStr }}</span>
          <span class="right-text">听过 {{ item.glance_count }}</span>
        </div>
      </li>
    </ul>
    <div v-if="typeof(this.qiangId) != 'undefined'" class="footer-action-btn">
      <button @click="cancel" class="cancel-btn">取消回答</button>
      <button @click="answer" :class="['confirm-btn', !canAnswer ? 'btn-disabled' : '']">回答</button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import qs from 'qs'

import Datetime from '@/util/datetime'
import Bubble from '@/components/bubble'
import ImagePreviewer from '@/components/imagePreviewer'

import Config from '@/config/config'

import { mapGetters } from 'vuex'

Vue.component(Bubble.name, Bubble)
Vue.component(ImagePreviewer.name, ImagePreviewer)

// 问题详情
export default {
  name: 'QuestionDetail',
  data () {
    return {
      id: this.$route.params.id,
      question: { asker: {} },
      answerData: { results: []},
      qiangId: this.$route.query.qiangId,
      countDown: '10:00',
      timer: null
    }
  },
  beforeDestroy () {
    if (this.timer) {
      window.clearInterval(this.timer)
      this.timer = null
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'isLogin',
      'localAnswers'
    ]),
    isAsker: function() {
      if (this.userInfo.id == this.question.asker.id) {
        return true
      } else {
        return false
      }
    },
    canAnswer: function() {
      var able = false
      if (this.userInfo.user_type == 2 && this.question.master_level && this.userInfo.level.sort >= this.question.master_level.sort) {
        able = true
      }
      // 已确认或者已关闭的任务不能回答
      if (this.question.process > 1) {
        able = false
      }
      // 自己不能回答
      if (this.userInfo.id == this.question.asker.id) {
        able = false
      }
      // 问答只能有三个答案
      if (this.question.type == 0 && this.answerData.results.length > 2) {
        able = false
      }
      // 点评不能超过3个答案
      if (this.question.type == 1 && this.answerData.results.length > 2) {
        able = false
      }
      for (var i=0; i<this.answerData.results.length; i++) {
        var item = this.answerData.results[i]
        if (item.replier.id == this.userInfo.id) {
          able = false
          break
        }
      }
      return able
    }
  },
  beforeCreate () {
    var webUrl = window.location.href
    var jsApiList = [
       "onMenuShareTimeline",
       "onMenuShareAppMessage",
    ]
    if (util.isAndroid()) {
      var that = this
      setTimeout(function() {
        that.SDKRegister(that, webUrl, jsApiList)
      }, 500)
    }
  },
  created () {
    if (typeof(this.$route.params.question) == 'undefined') {
      this.getQuestion()
    } else {
      this.question = this.$route.params.question
      this.setRemainHour()
    }
    if (typeof(this.qiangId) != 'undefined' && typeof(this.$route.params.qiang) == 'undefined') {
      this.getQiang()
    } else if (typeof(this.qiangId) != 'undefined' && typeof(this.$route.params.qiang) != 'undefined') {
      this.qiang = this.$route.params.qiang
      this.setTimer()
    }
    this.getAnswers()
    this.setShare()
  },
  methods: {
    getQuestion() {
      var url = '/dianping/question/' + this.id + '/'
      var that = this
      // 调用登陆接口
      this.axios.get(url)
      .then(function (res) {
        that.$toast.clear()
        that.question = res.data
        that.setRemainHour()
      })
      .catch(function (error) {
        that.$toast.clear()
        console.log(error)
      })
    },
    getQiang() {
      var url = '/dianping/qiang/' + this.qiangId + '/'
      var that = this
      // 调用登陆接口
      this.axios.get(url)
      .then(function (res) {
        that.$toast.clear()
        that.qiang = res.data
        that.setTimer()
      })
      .catch(function (error) {
        that.$toast.clear()
        console.log(error)
      })
    },
    getAnswers(next=null) {
      var params = { question: this.id }
      var url = '/dianping/answer/'
      if (next) {
        url = next
      }
      this.$toast.loading({ duration: 0 })
      var that = this
      // 调用登陆接口
      this.axios.get(url, { params: params })
      .then(function (res) {
        console.log(res)
        that.$toast.clear()
        if (res.status === 200) {
          that.answerData.results = res.data.results
          that.answerData.previous = res.data.previous
          that.answerData.next = res.data.next
          that.answerData.count = res.data.count
          // 把localId放到results里面去
          that.setLocalAudios(that.answerData.results)
          console.log(that.answerData.results)
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        console.log(error)
      })
    },
    setLocalAudios(answers) {
      var that = this
      console.log(this.localAnswers)
      answers.forEach(function(ans) {
        for (var i=0; i<that.localAnswers.length; i++) {
          var item = that.localAnswers[i]
          if (ans.id == item.id) {
            ans.localId = item.localId
            break
          }
        }
      })
    },
    answer: function() {
      if (this.userInfo.id == this.question.asker.id) {
        return this.$toast('不能回答自己发布的问题')
      }
      if (this.userInfo.user_type != 2) {
        return this.$toast("可前往'我的'认证为点评师后方可回答")
      }
      if (!this.canAnswer) {
        // 计算点评师的排序
        return
      }
      this.$router.push({ name: 'answer', params: { question: this.question} })
    },
    cancel: function() {
      // 若是抢，则取消抢
      if (typeof(this.qiangId) != 'undefined') {
        var that = this
        var url = '/dianping/qiang/' + this.qiangId + '/cancel/'
        this.$toast.loading()
        this.axios.post(url)
        .then(function (res) {
          that.$toast.clear()
          that.$router.go('-1')
        })
        .catch(function (error) {
          that.$toast.clear()
          if (error.response) {
            that.$toast.fail(error.response.data.detail)
          } else {
            that.$toast.fail('请求出错')
          }
        })
      } else {
        this.$router.go('-1')
      }
    },
    payAnswer: function(index) {
      var answer = this.answerData.results[index] 
      answer.is_bought = true
      answer.glance_count ++
    },
    setRemainHour: function() {
      var datetime = new Datetime(this.question.created)
      var pastSeconds = datetime.getPastSeconds()
      var hour = Math.floor(pastSeconds / 3600)
      var remainHour = 24 - hour
      if (remainHour < 1) {
        remainHour = 1
      }
      this.question.remainHour = remainHour
    },
    setTimer: function() {
      var that = this
      this.timer = setInterval(function() {
        var datetime = new Datetime(that.qiang.created) 
        var pastSeconds = datetime.getPastSeconds()
        var remainSeconds = 600 - pastSeconds
        if (remainSeconds <= 0) {
          that.countDown = '00:00'
        } else {
          var minute = Math.floor(remainSeconds / 60)
          var seconds = remainSeconds % 60
          if (minute < 10) {
            minute = '0' + minute
          }
          if (seconds < 10) {
            seconds = '0' + seconds
          }
          that.countDown = minute + ':' + seconds
        }
      }, 1000)
    },
    setShare: function() {
      var that = this
      var webUrl = window.location.href
      var route = webUrl.replace(Config.baseUrl, '')
      route = route.split('?')[0]
      this.wx.ready((res) => {
        var link = Config.baseUrl + '?route=' + route
        var title = ''
        var imgUrl = 'http://p2buepmu3.bkt.clouddn.com/works/2018/03/12/cb18b3197e1f4a63874beba400706f6d.jpg'
        if (that.question.attachments.length) {
          imgUrl = that.question.attachments[0]
        }
        if (that.answerData.results.length) {
          if (!that.userInfo) {
            title = '这个作品竟然得到了' + that.answerData.results[0].replier.nickname + '等老师的点评指导'
          } else {
            var isReplier = false
            for(var i=0; i<that.answerData.results.length; i++) {
              var item = that.answerData.results[i]
              if(item.replier.id == that.userInfo.id) {
                isReplier = true
                break
              }
            }
            if (isReplier) {
              title = '对这个书画作品，我谈了点看法，请各位批评指教'
            } else {
              title = '感谢' + that.answerData.results[0].replier.nickname + '等老师的点评指导'
            }
          }
        } else {
          title = '请各位大家进行点评指导'
        }
        var desc = that.question.text + '  ￥' + that.question.reward
        that.wx.onMenuShareTimeline({
          title: title, // 分享标题
          link: link, // 分享链接
          imgUrl: imgUrl, // 分享图标
          success () {
            that.$toast.success('分享成功')
          },
          cancel () {
          }
        })
        // 分享给朋友
        that.wx.onMenuShareAppMessage({
          title: title, // 分享标题
          desc: desc, // 分享描述
          link: link, // 分享链接
          imgUrl: imgUrl, // 分享图标
          success: function () {
            that.$toast.success('分享成功')
          },
          cancel: function () {
          }
        })
      })
    
    }
  }
}

</script>

<style lang="scss" scoped>
  @import '../../assets/style/const.scss';

  .question-answer-title {
    height: 41px;
    width: 100%;
    background: #fff;
    color: $color-text-normal;
    text-align: center;
    span {
      height: 41px;
      line-height: 41px;
      font-size: .7rem;
    }
  }
  .answer-action-wrapper {
    margin-top: 2px;
    background: #fff;
    padding: 0 .75rem;
    text-align: center;
    .action-btn {
      width: 3rem;
      height: 1.5rem;
      background: $color-red;
      border: none;
      color: #fff;
      border-radius: .75rem;
      margin: .75rem auto .5rem;
    }
    .btn-disabled {
      background: $color-royal;
    }
    .action-tips-wrapper {
      padding: .5rem 0;
      width: 100%;
      p {
        font-size: .6rem;
        line-height: .8rem;
        color: $color-text-desc;
      }
    }
  }
  .answers-wrapper {
    margin-top: .5rem;
  }
  .footer-action-btn {
    position: fixed;
    bottom: 0;
    height: 50px;
    width: 100%;
    font-size: 0;
    .cancel-btn {
      font-size: 14px;
      width: 50%;
      height: 100%;
      box-sizing: border-box;
      background: #fff;
      color: $color-text-strong;
      border: none;
      cursor: pointer;
    }
    .confirm-btn {
      font-size: 14px;
      width: 50%;
      height: 100%;
      box-sizing: border-box;
      background: $color-yellow;
      color: #fff;
      border: none;
      cursor: pointer;
    }
    .btn-disabled {
      background: #B5B5B5;
    }
  }
</style>
